import React, { useEffect, useState } from 'react';
import { useDispatch } from 'react-redux';
import { Button, Checkbox, Input, message, Upload } from 'tea-component';
import { useHistory } from "react-router-dom";

import timRenderInstance from '../../utils/timRenderInstance';
import { setIsLogInAction, userLogout, } from '../../store/actions/login';
import { clearConversation } from '../../store/actions/conversation';
import { clearHistory } from '../../store/actions/message';
import { updateHistoryMessageToStore } from '../../utils/LocalStoreInstance';
import { Avatar } from '../../components/avatar/avatar';
import { logoutParam } from 'im_electron_sdk/dist/interfaces';
import { useSettingConfig } from '../../utils/react-use/useSettingConfig';
import { updateSettingConfig } from '../../store/actions/config';
import Store from 'electron-store';
import { modifySlefUrl } from '../../api';
import { setUserInfo } from '../../store/actions/user';
import { EditIcon } from '../message/groupSetting/EditIcon';
import { useDialogRef } from '../../utils/react-use/useDialog';
import { ConfirmDialog, ConfirmDialogRecordsType } from '../message/groupSetting/ConfirmDialog';
import Toast from '../../components/toast/Toast';
import { _handleKickedout } from '../../utils/im-sdk';
const store = new Store();


export const AccountSetting = (): JSX.Element => {
    const history = useHistory();
    const dispatch = useDispatch();
    const [selfUserInfo, setSelfUserInfo] = useState<any>({})
    const [commRecvOpt,setCommRecvOpt] = useState(false);
    const [c2cRes,setC2cRes] = useState([]);
    const [groupRes,setGroupRes] = useState([]);
    const { userId, userSig,userName,userPwd, isAllowNotify,serverlist} = useSettingConfig();
    const [uploading, setUploading] = useState(null);
    const [isEdit, setIsEdit] = useState(false);
    const dialogRef = useDialogRef<ConfirmDialogRecordsType>();
    
    const logOutHandler = async () => {
        _handleKickedout();
        // let param:logoutParam = {};
        // await timRenderInstance.TIMLogout(param);
        // updateHistoryMessageToStore();
        // dispatch(userLogout());
        // history.replace('/login');
        // dispatch(setIsLogInAction(false));
        // dispatch(clearConversation())
        // dispatch(clearHistory())
    };

    const getSelfInfo = async () => {
        const d = await timRenderInstance.TIMGetLoginUserID();
        const userId = d.json_param;
        const  { code, json_param } = await timRenderInstance.TIMProfileGetUserProfileList({
            json_get_user_profile_list_param: {
                friendship_getprofilelist_param_identifier_array: [userId],
                friendship_getprofilelist_param_force_update:false,
            },
            user_data:""
        });

        if (code === 0) {
            const {
                user_profile_role: role,
                user_profile_face_url: faceUrl,
                user_profile_nick_name: nickName,
                user_profile_identifier: userId,
                user_profile_gender: gender,
                user_profile_self_signature: signature,
                user_profile_add_permission: addPermission
            } = json_param[0];
            setSelfUserInfo({
                userId,
                faceUrl,
                nickName,
                role,
                signature,
                gender,
                addPermission
            })
            setInput(nickName)
        }
    }
    async function  handleSuccess(result, { file }) {
        console.log(result);
        const res = await modifySlefUrl({faceurl: result.data.allPath});
        setUploading(false);
        let selfPro = selfUserInfo as any;
        selfPro.faceUrl = result.data.allPath;
        setSelfUserInfo(selfPro);
        dispatch(setUserInfo(selfPro));
    }
    const [input, setInput] = useState(selfUserInfo.nickName);
    const handleModify = async () => {
        const { code, desc, json_params }   = await timRenderInstance.TIMProfileModifySelfUserProfile({
            json_modify_self_user_profile_param:{user_profile_item_nick_name:input},
            user_data:"auto"
          });
        if (code === 0) {
            let selfPro = selfUserInfo as any;
            selfPro.nickName = input;
            setSelfUserInfo(selfPro);
            dispatch(setUserInfo(selfPro));
        }

    };
    function handleInput() {
        dialogRef.current.open({
          description: `是否将昵称修改为`,
          modifyContent: input,
          onConfirm: handleModify,
        });
    }
    const getCommRecType = async ()=>{
        const  { code, json_param }  = await timRenderInstance.TIMConvGetConvList({});
        let res = true;;
        const list = json_param;
        for(let i = 0;i<list.length;i++){
            const { conv_recv_opt } = list[i];
            if(conv_recv_opt != 2){
                res = false;
                break;
            }
        }
        groupIds(list);
        setCommRecvOpt(res);
    }
    const groupIds = (list)=>{
        const c2cRes = [];
        const groupRes = [];
   
        
        for(let i = 0;i<list.length;i++){
            const { conv_type,conv_id } = list[i]
            if(conv_type===1){
                // c2c
                c2cRes.push(conv_id)
            }
            if(conv_type === 2){
                // group
                groupRes.push(conv_id)
            }
        }
        setC2cRes(c2cRes)
        setGroupRes(groupRes)
    }
    const hasInfo = () => {
        return Object.keys(selfUserInfo).length > 0
    }
    const groupArray = (count,array) => {
        const array_copy = JSON.parse(JSON.stringify(array));
        const res = [];
        res.push(array_copy.splice(0,count));
        console.log(res)
        if(array_copy.length){
            const left = groupArray(count,array_copy);
            for(let j = 0;j<left.length;j++){
                res.push(left[j])
            }
        }
        return res;
    }
    const commNotiyOptValueChange =(isNotty)=>{
        dispatch(updateSettingConfig({
            userId,
            userSig,
            userName,
            userPwd,serverlist,
            isAllowNotify:!isNotty
        }));
        store.set('setting-config', {
            userId,
            userSig,
            userName,
            userPwd,
            isAllowNotify:!isNotty
        });
    }
    const commRecvOptValueChange = async (isRecv)=>{
        let isSet = false;
        if(isRecv){
            isSet = true;
        }
        const cg = groupArray(30,c2cRes);
        for(let i = 0;i<cg.length;i++){
            await timRenderInstance.TIMMsgSetC2CReceiveMessageOpt({
                params: cg[i],
                opt: isSet ? 2 : 0,
                // hide_tips:true
            })
        }
        for(let i = 0;i<groupRes.length;i++){
            await timRenderInstance.TIMMsgSetGroupReceiveMessageOpt({
                group_id: groupRes[i],
                opt: isSet ? 2 : 0,
                // hide_tips:true
            })
        }
        
        setCommRecvOpt(isRecv);
    }
    useEffect(() => {
        getSelfInfo();
        getCommRecType();
    }, [])
    function handleStart() {
        setUploading(true);
    }
    function handleError(error, { file }) {
        message.error(error);
        setUploading(false);
    }
    return (
        <div className="connect">
            <header className="connect-header">
                <span className="connect-header--logo"></span>
                <span className="connect-header--text">账号设置</span>
            </header>
            <section className="connet-section">
                <div>
                    <div>账号信息：</div>
                    {
                        hasInfo() ? (
                            <div className='info-panel'>
                                <div className='info-avatar'>
                                    <Avatar url={selfUserInfo.faceUrl} userID={selfUserInfo.UID}></Avatar>
                                </div>
                                <div className='info-name'>
                                    <p style={{fontSize:"20px"}}>{selfUserInfo.nickName} <EditIcon  onClick={() =>setIsEdit(!isEdit)} /></p>
                                    {isEdit && (
                                        <Input  className="group-introduction--input"  size="full"  placeholder="输入后群名称后按回车进行设置"  value={input}
                                            onChange={(value) => {
                                                setInput(value);
                                            }}
                                            onBlur={handleInput}
                                            onKeyDown={(e) => {
                                                if (e.key === "Enter") {
                                                    handleInput();
                                                }
                                            }}
                                        />
                                        )}
                                </div>
                                <div className='info-out' style={{display:"flex"}}>
                                    <Upload action={Toast.defaultser +"/api/app/file/uploadImage" } accept={["image/jpeg","image/png"]} maxSize={2048 * 2048}
                                        onStart={handleStart}  onSuccess={handleSuccess}  onError={handleError}>
                                        <Button loading={uploading}>更换头像</Button>
                                    </Upload>
                                    <Button onClick={logOutHandler} style={{  marginLeft: "10px" }}>退出登录</Button>
                                </div>
                            </div>
                        ) : null
                    }
                </div>
                <div>
                    <div>消息：</div>
                    <div  className='info-panel' style={{flexDirection:"column"}}>
                        <Checkbox value={commRecvOpt} onChange={commRecvOptValueChange}>PC端在线时移动端不接受离线推送</Checkbox>
                        <Checkbox value={!isAllowNotify} onChange={commNotiyOptValueChange}>关闭消息通知</Checkbox>
                    </div>
                </div>
            </section>
            <ConfirmDialog  dialogRef={dialogRef}  onSuccess={() => {
                setIsEdit(false);
                }}
            />
        </div>
    )
}